package com.winterchen.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.winterchen.dao.UserDao;
import com.winterchen.model.UserDomain;
import com.winterchen.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.rmi.runtime.Log;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by Administrator on 2017/8/16.
 */
@Service(value = "userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;//这里会报错，但是并不会影响
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public int addUser(UserDomain user) {
        return userDao.insert(user);
    }

    /*
    * 这个方法中用到了我们开头配置依赖的分页插件pagehelper
    * 很简单，只需要在service层传入参数，然后将参数传递给一个插件的一个静态方法即可；
    * pageNum 开始页数
    * pageSize 每页显示的数据条数
    * */
    @Override
    public PageInfo<UserDomain> findAllUser(int pageNum, int pageSize) {
        //将参数传给这个方法就可以实现物理分页了，非常简单。
        PageHelper.startPage(pageNum, pageSize);
        List<UserDomain> userDomains = userDao.selectUsers();
        PageInfo<UserDomain> pageInfo = new PageInfo<>(userDomains);
        // 具体使用
        redisTemplate.opsForList().leftPush("user:list", userDomains.toString());
        stringRedisTemplate.opsForValue().set("user:name", "张三");
        List<String> list = new ArrayList<>();
        list.add("1");
        list.add("1");
        list.add("2");
        redisTemplate.opsForSet().add("user:ceshi",list.toString());
        Object o = redisTemplate.opsForSet().pop("user:ceshi");
        if(null == o) {
            System.out.println("没有值");
        }
        List<String> strings = Arrays.asList(o.toString());
        strings.forEach(x -> System.out.println(x));
        return pageInfo;
    }

    @Override
    public int deleteById(UserDomain user) {
        return userDao.deleteById(user);
    }

    @Override
    @Transactional
    public int addAndDelete(UserDomain user) {
        userDao.insert(user);
        int i = 1 / 0;
        return userDao.deleteById(user);
    }
}
